﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Show1
{
    public partial class FrmLogin : Form
    {
        public FrmLogin()
        {
            InitializeComponent();
        }

        private void btnLogin_Click(object sender, EventArgs e)
        {          
            string name = txtLoginName.Text;
            string pwd = txtPwd.Text;

            if (name.Length==0)
            {
                MessageBox.Show("请输入用户名", "非空验证", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;//终止整个方法
            }

            if (pwd.Length <6)
            {
                MessageBox.Show("密码长度必须足够6", "非空验证", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;//终止整个方法
            }

            //连接数据库
            string sql =string.Format( "select count(0) from userinfo where loginname='{0}' and loginpwd='{1}'",name,pwd);

            SqlConnection conn = new SqlConnection(@"Data Source=.\sqlexpress;Initial Catalog=MySchoolBase;Integrated Security=True");
            try
            {
                conn.Open();
                SqlCommand cmd = new SqlCommand(sql, conn);
                 int count =(int)cmd.ExecuteScalar();
                 if (count > 0)
                 {
                     MessageBox.Show("登录成功");
                     FrmMain frm = new FrmMain();//新建一个主窗体
                     frm.loginName = name;//把登录名传过去
                     frm.Show();//打开主窗体
                     //this.Close();//一旦把第一个窗体关掉，那整个程序都会退出
                     this.Hide();//隐藏登录窗体
                 }
                 else
                 {
                     MessageBox.Show("登录失败");
                 }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                conn.Close();
            }
        }

        //点击取消按钮
        private void btnCancel_Click(object sender, EventArgs e)
        {
            DialogResult dr =  MessageBox.Show("确定退出登录吗？",
                "退出确认",
                MessageBoxButtons.OKCancel,
                MessageBoxIcon.Warning);
            if (dr == System.Windows.Forms.DialogResult.OK)//如果用户点了确定
            {
                this.Close();
            }
        }
    }
}
